package com.ydm.myapp001.activity;

import android.app.ActivityManager;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

import com.ydm.myapp001.R;


public class SystemCommonServiceActivity extends AppCompatActivity {
    private Context mContext;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        //setContentView(R.layout.activity_system_common_service);
        //用LayoutInflater服务获取一个View传入setContentView中
        LayoutInflater layoutInflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
        View view = layoutInflater.inflate(R.layout.activity_system_common_service, null);
        setContentView(view);
    }


    public void doClick(View v) {
        switch(v.getId()){
            case R.id.btn_network: {
                if (isNetWorkConnected(mContext)) {
                    Toast.makeText(mContext, "网络已经连接", Toast.LENGTH_SHORT).show();
                }
                else {
                    Toast.makeText(mContext, "网络未连接", Toast.LENGTH_SHORT).show();
                }
            }
                break;
            case R.id.btn_enableOrDisable_WIFI: {
                WifiManager wifiManager = (WifiManager) mContext.getSystemService(WIFI_SERVICE);
                if (wifiManager.isWifiEnabled()) {
                    wifiManager.setWifiEnabled(false);
                    Toast.makeText(mContext, "Wifi已经关闭", Toast.LENGTH_SHORT).show();
                }
                else {
                    wifiManager.setWifiEnabled(true);
                    Toast.makeText(mContext, "Wifi已经打开", Toast.LENGTH_SHORT).show();
                }
            }
                break;
            case R.id.btn_getPackagename: {
                ActivityManager activityManager = (ActivityManager) mContext.getSystemService(ACTIVITY_SERVICE);
                String name = activityManager.getRunningTasks(1).get(0).topActivity.getPackageName();
                Toast.makeText(mContext, "当前运行的Activity的包名:"+name, Toast.LENGTH_SHORT).show();
            }
                break;
            default:
                break;
        }
    }


    public boolean isNetWorkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);
            NetworkInfo mNetWorkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetWorkInfo != null) {
                return mNetWorkInfo.isAvailable();
            }
        }

        return false;
    }
}
